<template>
    <el-container class="app-container">
        <el-header height="40px" style="padding: 15px;">
            <el-row>
                <el-col :span="12">
                    <el-button type="primary" plain icon="Plus" size="small" @click="handleAdd">
                        新增
                    </el-button>
                    <el-button type="primary" plain icon="Refresh" size="small" @click="handleRefresh">刷新</el-button>
                </el-col>
            </el-row>
        </el-header>
        <el-main>
            <el-table ref="tableRef" v-loading="loading" :data="menuList" row-key="id" :default-expand-all="isExpandAll"
                size="small" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true"
                    width="160"></el-table-column>
                <el-table-column prop="icon" label="图标" align="center" width="100">
                    <template v-slot="{ row }">
                        <KuiIcon :name="row.icon" />
                    </template>
                </el-table-column>
                <el-table-column prop="menuType" label="菜单类型" width="100">
                    <template v-slot="{ row }">
                        <el-tag v-if="row.menuType === 'dir'" type="info">目录</el-tag>
                        <el-tag v-else-if="row.menuType === 'menu'" type="success">菜单</el-tag>
                        <el-tag v-else-if="row.menuType === 'button'" type="warning">按钮</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="orderNum" label="排序" width="60"></el-table-column>
                <el-table-column prop="routeName" label="路由名称" :show-overflow-tooltip="true"
                    width="150"></el-table-column>
                <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"
                    width="180"></el-table-column>
                <el-table-column prop="path" label="路由地址" :show-overflow-tooltip="true" width="180"></el-table-column>
                <el-table-column prop="status" label="状态" width="80">
                    <template v-slot="scope">
                        <el-tag type="success" v-if="scope.row.status === '1'">正常</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.status === '0'">禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="visible" label="是否显示" width="100">
                    <template v-slot="scope">
                        <el-tag type="success" v-if="scope.row.visible === '1'">是</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.visible === '0'">否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createdAt" width="150">
                    <template v-slot="scope">
                        {{ parseTime(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                    <template v-slot="scope">
                        <el-button size="small" type="text" icon="el-icon-edit" style="padding: 1px;margin-left: 5px;"
                            @click="handleUpdate(scope.row)">修改</el-button>
                        <el-button size="small" type="text" icon="el-icon-plus" style="padding: 1px;margin-left: 5px;"
                            @click="handleAdd(scope.row)">新增</el-button>
                        <el-button size="small" type="text" icon="el-icon-delete" style="padding: 1px;margin-left: 5px;"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>

        <!-- 添加或修改菜单对话框 -->
        <el-drawer :title="title" v-model="detailDialogVisible" :size="800" append-to-body>
            <el-form ref="menuFormRef" :model="menuFormData" :rules="menuFormRules" label-width="100px"
                label-suffix=":">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级菜单" prop="parentId">
                            <el-tree-select v-model="menuFormData.parentId" :data="menuOptions" :check-strictly="true"
                                :render-after-expand="false" placeholder="选择上级菜单" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="菜单类型" prop="menuType">
                            <el-radio-group v-model="menuFormData.menuType" @change="changeMenuType">
                                <el-radio value="dir">目录</el-radio>
                                <el-radio value="menu">菜单</el-radio>
                                <!-- <el-radio value="button">按钮</el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="菜单名称" prop="menuName">
                            <el-input v-model="menuFormData.menuName" placeholder="请输入菜单名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="menuFormData.menuType != 'button'">
                        <el-form-item label="菜单图标" prop="icon">
                            <KuiIconSelect v-model="menuFormData.icon" />
                            <!-- <el-input v-model="menuFormData.icon" placeholder="参考ElementPlus/icons"></el-input> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="显示排序" prop="orderNum">
                            <el-input-number v-model="menuFormData.orderNum" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="menuFormData.menuType == 'menu'">
                        <el-form-item prop="outerLink" label="是否外链">
                            <el-radio-group v-model="menuFormData.outerLink">
                                <el-radio label="1">是</el-radio>
                                <el-radio label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <template v-if="menuFormData.outerLink == '0'">
                        <el-col :span="24" v-if="menuFormData.menuType == 'menu'">
                            <el-form-item prop="routeName" label="路由名称">
                                <!-- 默认不填则和路由地址相同：如地址为：`user`，则名称为`User`（注意：为避免名字的冲突，特殊情况下请自定义，保证唯一性） -->
                                <el-input v-model="menuFormData.routeName" placeholder="请输入路由名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="menuFormData.menuType == 'menu'">
                            <el-form-item prop="path">
                                <template #label>
                                    <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                    路由地址
                                </template>
                                <el-input v-model="menuFormData.path" placeholder="请输入路由地址" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="menuFormData.menuType == 'menu'">
                            <el-form-item prop="component">
                                <template #label>
                                    <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                    组件路径
                                </template>
                                <el-input v-model="menuFormData.component" placeholder="请输入组件路径">
                                    <template #prepend>@/views/</template>
                                    <template #append>.vue</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="menuFormData.menuType != 'dir'">
                            <el-form-item prop="perms">
                                <el-input v-model="menuFormData.perms" placeholder="请输入权限标识" maxlength="100" />
                                <template #label>
                                    <el-tooltip
                                        content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                                        placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                    权限字符
                                </template>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="menuFormData.menuType == 'menu'">
                            <el-form-item prop="query">
                                <el-input v-model="menuFormData.query" placeholder="请输入路由参数" maxlength="255" />
                                <template #label>
                                    <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                    路由参数
                                </template>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="menuFormData.menuType == 'menu'">
                            <el-form-item prop="cacheFlag">
                                <template #label>
                                    <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                                        <i class="el-icon-question"></i>
                                    </el-tooltip>
                                    是否缓存
                                </template>
                                <el-radio-group v-model="menuFormData.cacheFlag">
                                    <el-radio value="0">缓存</el-radio>
                                    <el-radio value="1">不缓存</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template v-else>
                        <el-col :span="24" v-if="menuFormData.menuType == 'menu'">
                            <el-form-item prop="path" label="链接地址">
                                <el-input v-model="menuFormData.path" placeholder="请输入链接地址" />
                            </el-form-item>
                        </el-col>
                    </template>

                    <el-col :span="24" v-if="menuFormData.menuType != 'button'">
                        <el-form-item prop="visible" label="显示状态">
                            <el-radio-group v-model="menuFormData.visible">
                                <!-- 选择隐藏则路由将不会出现在侧边栏，但仍然可以访问 -->
                                <el-radio value="1">显示</el-radio>
                                <el-radio value="0">隐藏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item prop="status" label="菜单状态">
                            <!-- 选择停用则路由将不会出现在侧边栏，也不能被访问 -->
                            <el-radio-group v-model="menuFormData.status">
                                <el-radio value="1">启用</el-radio>
                                <el-radio value="0">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancelForm">取 消</el-button>
            </div>
        </el-drawer>
    </el-container>
</template>

<script>
import menu from '@/api/menu';
import http from '@/api/http';
export default {
    name: 'SysMenuView',
    data() {
        return {
            loading: false,
            isExpandAll: false,
            menuFormData: {
                id: null,
                parentId: 0,
                menuType: 'dir',
                icon: '',
                menuName: '',
                routeName: '',
                outerLink: '1',
                cacheFlag: '0',
                query: '',
                orderNum: 0,
                visible: '1',
                status: '1'
            },
            menuFormRules: {
                menuType: [
                    { required: true, message: '请选择菜单类型', trigger: 'change' }
                ],
                menuName: [
                    { required: true, message: '请输入菜单名称', trigger: 'blur' }
                ],
                orderNum: [
                    { required: true, message: '请输入排序号', trigger: 'blur' }
                ],
                routeName: [
                    { required: true, message: '请输入路由名称', trigger: 'blur' }
                ],
                path: [
                    { required: true, message: '请输入路由(链接)地址', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择菜单状态', trigger: 'change' }
                ],
                visible: [
                    { required: true, message: '请选择菜单可见性', trigger: 'change' }
                ]
            },
            menuOptions: [],
            menuList: [],
            detailDialogVisible: false,
            title: ''
        }
    },
    mounted() {
        // 初始化菜单列表
        this.getList();
    },
    methods: {
        getList() {
            this.loading = true;
            menu.getMenuListTree().then((response) => {
                this.menuList = response.data;

                // 构建menuOptions
                this.menuOptions = response.data.map(menu => ({
                    id: menu.id,
                    label: menu.menuName,
                    value: menu.id,
                    children: menu.children ? menu.children.map(child => ({
                        id: child.id,
                        label: child.menuName,
                        value: child.id
                    })) : []
                }));
            }).catch((error) => {
                console.error("Error fetching menu list:", error);
            }).finally(() => {
                this.loading = false;
            });
        },
        handleRefresh() {
            this.getList();
        },
        handleAdd(row) {
            this.detailDialogVisible = true;
            this.title = row ? '新增子菜单' : '新增菜单';
            this.menuFormData = {
                id: null,
                parentId: row ? row.id : 0,
                menuType: 'dir',
                icon: '',
                orderNum: 0,
                menuName: '',
                routeName: '',
                outerLink: '1',
                cacheFlag: '0',
                query: '',
                visible: '1',
                status: '1'
            };
        },
        handleUpdate(row) {
            this.detailDialogVisible = true;
            this.title = '修改菜单';
            this.menuFormData = { ...row };
        },
        submitForm() {
            this.$refs.menuFormRef.validate((valid) => {
                if (!valid) {
                    console.error("Form validation failed");
                    return;
                }

                http.post('/sys/menu', this.menuFormData)
                    .then(() => {
                        this.detailDialogVisible = false;
                        this.getList();
                        this.sendMenuChangeMessage();
                    })
                    .catch((error) => {
                        console.error("Error saving menu:", error);
                    })
                    .finally(() => {
                    });

            });
        },
        cancelForm() {
            this.detailDialogVisible = false;
            this.menuFormData = {
                id: null,
                parentId: 0,
                menuType: 'dir',
                icon: '',
                orderNum: 0,
                menuName: '',
                routeName: '',
                outerLink: '1',
                cacheFlag: '0',
                query: '',
                visible: '1',
                status: '1'
            };
        },
        handleDelete(row) {
            this.$confirm('Are you sure you want to delete this menu?', 'Warning', {
                confirmButtonText: 'Delete',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {
                http.delete(`/sys/menu/${row.id}`).then(() => {
                    this.$message.success('Menu deleted successfully');
                    this.getList();
                    this.sendMenuChangeMessage();
                });
            }).catch(() => { });
        },
        parseTime(time) {
            if (!time) return '-';
            const date = new Date(time);
            return date.toLocaleString();
        },
        sendMenuChangeMessage() {
            this.$bus.emit('menuChangeEvent', {});
        },
        changeMenuType(val) {
            if (val === 'dir') {
                this.menuFormData = {
                    ...this.menuFormData,
                    routeName: '',
                    outerLink: '',
                    cacheFlag: '',
                    query: '',
                }
            } else if (val === 'menu') {
                this.menuFormData = {
                    ...this.menuFormData,
                    routeName: '',
                    outerLink: '0',
                    cacheFlag: '1',
                    query: '',
                }
            } else {

            }
        },
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    background-color: #ffffff;
}
</style>
